import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { message, Upload } from 'antd';
import ImgCrop from 'antd-img-crop';
import type { RcFile,UploadFile, UploadProps } from 'antd/es/upload/interface';
import React, {useEffect, useState} from 'react';

import {baceUrl} from "../../utils/config";

const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'|| file.type === 'image/gif';
    if (!isJpgOrPng) {
        message.error('只可以上传 JPG/PNG/GIF 格式!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('图片不可超过2M!');
    }
    return isJpgOrPng && isLt2M;
}

const UserInfoImages=(props:any)=> {
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();

    const handleChange: UploadProps['onChange'] = (info:any) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            setLoading(false);
            props.obtainImg(info.file.response.data)
            setImageUrl(baceUrl+info.file.response.data)
        }
    };
    useEffect(()=>{
        setImageUrl(props.urlpass?baceUrl+props.urlpass:'')
    },[])
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
        </div>
    );
    const [token,]:any = useState({Authorization: sessionStorage.getItem('token')})
    return (
        <ImgCrop rotate>
            <Upload
                name="file"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action="http://estate.eshareedu.cn/estate/api/upload/add"
                headers={token}
                beforeUpload={beforeUpload}
                onChange={handleChange}
            >
                {imageUrl ? <img src={imageUrl} alt="显示错误" style={{ width: '100%' }} /> : uploadButton}
            </Upload>
        </ImgCrop>
    );
}

export default UserInfoImages;
